package com.abc.robot01.view

import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.BlurEffect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Fill
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintLayout
import com.abc.robot01.R
import com.abc.robot01.activity.MYBLACK
import com.abc.robot01.activity.MYBLACK_Percent80
import com.abc.robot01.activity.mysp
import com.abc.robot01.activity.px
import com.abc.robot01.retrofit.bean.GlobalState
import kotlin.math.abs

class DraggableConstraintLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : ViewGroup(context, attrs, defStyleAttr) {

    fun setSpClick(click:()->Unit ={}){
        SpClick = click
    }

    fun setInfoClick(click:()->Unit ={}){
        InfoClick = click
    }

    fun setHomeClick(click:()->Unit ={}){
        HomeClick = click
    }

    fun setFaClick(click:()->Unit ={}){
        FaClick = click
    }


   private var SpClick:()->Unit ={}

    private var InfoClick:()->Unit ={}

    private var HomeClick:()->Unit ={}

    private var FaClick:()->Unit ={}



    val TAG="DraggableConstraintLayout"

    private lateinit var root2 :ComposeView
//    private lateinit var sp: View
    private var lastX = 0f
    private var lastY = 0f

    private var contentVisible = true

    private lateinit var constraintLayout: ConstraintLayout

    @Composable
    fun BoxWithCircleBackground(
        color:Color =Color.White,
        selected:Boolean = false,
        modifier:Modifier,
        text:String,
        @DrawableRes img: Int, @DrawableRes press: Int,onClick: ()->Unit) {
        // 记录 Box 的点击状态
        var isPressed by remember { mutableStateOf(false) }
        Box(
            contentAlignment=Alignment.Center,
            modifier = modifier
                .clickable {
                    Log.e(TAG, "BoxWithCircleBackground onClick ");

                }
                .size(120.px) // 直径为 240，半径为 120
                .background(
                    color = Color.Black.copy(alpha = if (isPressed.not()) 0.6f else 0.8f), // 60% 透明度的黑色
                    shape = CircleShape // 使用圆形形状
                )
                .pointerInput(Unit) {
                    detectTapGestures(
                        onPress = {
                            isPressed = true
                            try {
                                awaitRelease()
                            } finally {
                                isPressed = false
                                onClick();
                            }
                        }
                    )
                }
        ) {
            // 在Box的中心绘制一个100x100的圆
if(selected) {
    Canvas(
        modifier = Modifier
            .align(Alignment.Center)
    ) {
        drawCircle(
            color = Color.White,
            radius = 50f // 半径为 50，直径为 100
        )
    }
}

            Column(horizontalAlignment=Alignment.CenterHorizontally) {
                Image(painter = painterResource(id = img) , contentDescription = "")
                Spacer(modifier = Modifier.height(10.px))
                Text(text = text, fontSize = 24.mysp, color = color)
            }
        }
    }

    @Composable
    fun ConstraintLayoutContent() {
        var selected1 by  remember {  GlobalState.selected10 }
        var selected2 by  remember {  GlobalState.selected2 }
        var selected3 by  remember {  GlobalState.selected3 }
        var selected4 by  remember {  GlobalState.selected4 }

        ConstraintLayout {
            val (home,sp, info,fa) = createRefs()
            BoxWithCircleBackground(
                selected= selected4,
                color= if(selected4) MYBLACK_Percent80 else Color.White ,
                text="方案",
                img = if(!selected4) R.drawable.fa1 else R.drawable.fa2,
                press = R.drawable.fa2,
                modifier = Modifier.constrainAs(fa){
                start.linkTo(parent.start, margin = 275.px)
                top.linkTo(parent.top)
            }
            ){
                selected4 = true
                selected1 = false
                selected2 = false
                selected3 = false
                FaClick()
            }
            BoxWithCircleBackground(
                selected= selected3,
                color= if(selected3) MYBLACK_Percent80 else Color.White ,
                text="信息",
                img = if(!selected3) R.drawable.info1 else R.drawable.info2,
                press = R.drawable.info2,
                modifier = Modifier.constrainAs(info){
                    start.linkTo(parent.start, margin = 140.px)
                    top.linkTo(parent.top, margin = 38.px)
                }){
                selected3 = true
                selected1 = false
                selected2 = false
                selected4 = false
                InfoClick()
            }
            BoxWithCircleBackground(
                color= if(selected2) MYBLACK_Percent80 else Color.White ,
                selected= selected2,
                text="商品",
                img = if(!selected2) R.drawable.sp1 else R.drawable.sp2,
                press = R.drawable.sp2,
                modifier = Modifier.constrainAs(sp){
                    start.linkTo(parent.start, margin = 35.px)
                    top.linkTo(parent.top, margin = 142.px)
                }){
                selected2 = true
                selected1 = false
                selected3 = false
                selected4 = false
                SpClick()
            }
            BoxWithCircleBackground(
                color= if(selected1) MYBLACK_Percent80 else Color.White ,
                selected= selected1,
                text= stringResource(id = R.string.home),
                img = if(!selected1) R.drawable.home1 else R.drawable.home2,
                press = R.drawable.home2,
                modifier = Modifier.constrainAs(home){
                    start.linkTo(parent.start)
                    top.linkTo(parent.top, margin = 282.px)
                }){
                selected1 = true
                selected2 = false
                selected3 = false
                selected4 = false
                Log.e(TAG,"onclick HomeClick")
                HomeClick()
            }
        }
    }

    @Composable
    fun DrawTransparentCircleInBox() {
        // 将 Box 的大小设置为 148x148
        Box(modifier = Modifier
            .size(148.px)
            // 应用模糊效果，模糊半径为30
            .graphicsLayer {
                renderEffect = BlurEffect(radiusX = 5f, radiusY = 5f)
            }
        ) {
            Canvas(modifier = Modifier.fillMaxSize()) {
                // 画一个半径为74的圆，透明度为40%的黑色
                drawCircle(
                    color = Color.Black.copy(alpha = 0.4f), // 40%透明度的黑色
                    radius = 74.0f, // 圆的半径为148
                    center = center, // 圆心为画布的中心
                    style = Fill // 使用填充样式
                )
                // 画一个半径为49的白色环，透明度为30%，宽度为4
                drawCircle(
                    color = Color.White.copy(alpha = 0.3f), // 30%透明度的白色
                    radius = 49f, // 圆的半径为49
                    center = center, // 圆心为画布的中心
                    style = Stroke(width = 4f) // 使用Stroke样式，宽度为4
                )

                // 画一个半径为32的白色环，宽度为4，不透明
                drawCircle(
                    color = Color.White, // 不透明的白色
                    radius = 32f, // 圆的半径为32
                    center = center, // 圆心为画布的中心
                    style = Stroke(width = 4f) // 使用Stroke样式，宽度为4
                )
            }
        }
    }

    override fun onFinishInflate() {
        super.onFinishInflate()
        constraintLayout = findViewById(R.id.root1)
          root2 =  findViewById(R.id.root2)

        root2.setContent {
            ConstraintLayoutContent()
        }

           val  toggle = findViewById<ComposeView>(R.id.toggle)

        toggle.setContent {
            DrawTransparentCircleInBox()
        }
        val  onClick = {
            if(root2.visibility== VISIBLE){
                Log.e(TAG,"onclick INVISIBLE")
                root2.visibility = INVISIBLE
                contentVisible = false
            }
            else{
                root2.visibility = VISIBLE
                contentVisible = true
                Log.e(TAG,"onclick VISIBLE")
            }
        }

        toggle.setOnTouchListener(object : View.OnTouchListener {
            private var initialTouchX: Float = 0f
            private var initialTouchY: Float = 0f

            private var initialTouchX2: Float = 0f
            private var initialTouchY2: Float = 0f


            private val clickThreshold = 3 // Threshold for detecting click vs drag

            override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
                when (motionEvent.action) {
                    MotionEvent.ACTION_DOWN -> {
                        initialTouchX = motionEvent.rawX
                        initialTouchY = motionEvent.rawY

                        initialTouchX2 = motionEvent.rawX
                        initialTouchY2 = motionEvent.rawY
                        return true
                    }

                    MotionEvent.ACTION_MOVE -> {
                        val deltaX = (motionEvent.rawX - initialTouchX)
                        val deltaY = (motionEvent.rawY - initialTouchY)
                        if (abs(deltaX) > clickThreshold || abs(deltaY) > clickThreshold) {
                            constraintLayout.translationX += deltaX
                            constraintLayout.translationY += deltaY
                            initialTouchX = motionEvent.rawX
                            initialTouchY = motionEvent.rawY
                        }
                        return true
                    }

                    MotionEvent.ACTION_UP -> {
                        val deltaX = (motionEvent.rawX - initialTouchX2).toInt()
                        val deltaY = (motionEvent.rawY - initialTouchY2).toInt()
                        if (abs(deltaX) < clickThreshold && abs(deltaY) < clickThreshold) {
                            onClick();
                            // It was a click, not a drag
                        }
                        return true
                    }
                }
                return false
            }
        })
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        measureChild(constraintLayout, widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(
            resolveSize(constraintLayout.measuredWidth, widthMeasureSpec),
            resolveSize(constraintLayout.measuredHeight, heightMeasureSpec)
        )
    }

    override fun onLayout(p0: Boolean, l: Int, t: Int, r: Int, b: Int) {
        // Layout the ConstraintLayout
        constraintLayout.layout(0, 0, constraintLayout.measuredWidth, constraintLayout.measuredHeight)
    }

    private var  injected= false;

    private var  move= false;

    override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
      when(event.action){
          MotionEvent.ACTION_DOWN -> {
              val location = IntArray(2)
              root2.getLocationOnScreen(location)
              val imageViewX = location[0]
              val imageViewY = location[1]
              val imageViewWidth = root2.width
              val imageViewHeight = root2.height
              // Check if the touch event is within the ImageView's bounds
              if (event.rawX >= imageViewX && event.rawX <= (imageViewX + imageViewWidth) &&
                  event.rawY >= imageViewY && event.rawY <= (imageViewY + imageViewHeight)
              ) {
//                  Log.e(TAG,"onInterceptTouchEvent   return true")
//                  return true
              }
          }
          else -> {
//              Log.e(TAG,"onInterceptTouchEvent   return false")
//              return false
          }
      }
        Log.e(TAG,"onInterceptTouchEvent   return false")
        return false
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
//        Log.e(TAG,"onTouchEvent:"+event)
//        BaseActivity.a?.inject(event);
        if (event.action == MotionEvent.ACTION_DOWN) {
            if(contentVisible) {
                val location = IntArray(2)
                root2.getLocationOnScreen(location)
                val imageViewX = location[0]
                val imageViewY = location[1]
                val imageViewWidth = root2.width
                val imageViewHeight = root2.height
                // Check if the touch event is within the ImageView's bounds
                if (event.rawX >= imageViewX && event.rawX <= (imageViewX + imageViewWidth) &&
                    event.rawY >= imageViewY && event.rawY <= (imageViewY + imageViewHeight)
                ) {
                    injected = false
                    move = true
                    // The touch event is within the ImageView
                    // Handle the event here
                    // Example: perform a specific action
                } else {
//                    Log.e(TAG,"inject 1 (event):"+event)
                    injected = true
                    return false;
                }
            }
            else{
//                Log.e(TAG,"inject 2 (event):"+event)
                injected = true
                return false;
            }
        } else{
            if(injected){
//                Log.e(TAG,"inject 3 (event):"+event)
                return false;
            }
        }

        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                lastX = event.rawX
                lastY = event.rawY
            }
            MotionEvent.ACTION_MOVE -> {
                val dx = event.rawX - lastX
                val dy = event.rawY - lastY
                if(move) {
                    if(constraintLayout.translationX+dx<=1920-409 && constraintLayout.translationX+dx >=0){
                        constraintLayout.translationX += dx
                        lastX = event.rawX
                    }
                    if(constraintLayout.translationY+dy<=1080-416 && constraintLayout.translationY+dy>=0){
                        constraintLayout.translationY += dy
                        lastY = event.rawY
                    }
                }
            }
            MotionEvent.ACTION_UP ->{
                injected = false
                move = false
            }
        }
        return true
    }
}

fun Activity.enableFaClick(onClick: () -> Unit) {
    findViewById<DraggableConstraintLayout>(R.id.floating).setFaClick {
        onClick();
    }
}

fun Activity.enableSpClick(onClick: () -> Unit) {
    findViewById<DraggableConstraintLayout>(R.id.floating).setSpClick {
        onClick()
    }
}

fun Activity.enableInfoClick(onClick: () -> Unit) {
    findViewById<DraggableConstraintLayout>(R.id.floating).setInfoClick {
        onClick()
    }
}

fun Activity.enableHomeClick(onClick: () -> Unit) {
    findViewById<DraggableConstraintLayout>(R.id.floating).setHomeClick{
        onClick()
    }
}




